<template>
  <view class="profile-container">
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-bg"></view>
      <view class="user-info">
        <view class="avatar-section" @click="changeAvatar">
          <image class="user-avatar" :src="userInfo.avatar || defaultAvatar" mode="aspectFill"></image>
          <view class="avatar-edit">
            <text class="edit-icon">✎</text>
          </view>
        </view>
        <view class="user-details">
          <text class="user-name">{{ userInfo.username || '未设置用户名' }}</text>
          <text class="user-email">{{ userInfo.email || '未设置邮箱' }}</text>
          <text class="user-phone">{{ userInfo.phone || '未设置手机号' }}</text>
        </view>
        <view class="edit-profile" @click="editProfile">
          <text class="edit-text">编辑资料</text>
        </view>
      </view>
    </view>

    <!-- 账户概览 -->
    <view class="account-overview">
      <view class="overview-title">账户概览</view>
      <view class="overview-grid">
        <view class="overview-item" @click="viewRecords(1)">
          <text class="overview-number">{{ statistics.totalRecords || 0 }}</text>
          <text class="overview-label">记账总数</text>
        </view>
        <view class="overview-item" @click="viewRecords(1)">
          <text class="overview-number">{{ statistics.incomeRecords || 0 }}</text>
          <text class="overview-label">收入记录</text>
        </view>
        <view class="overview-item" @click="viewRecords(0)">
          <text class="overview-number">{{ statistics.expenseRecords || 0 }}</text>
          <text class="overview-label">支出记录</text>
        </view>
        <view class="overview-item" @click="navigateToStatistics">
          <text class="overview-number" :class="{ positive: statistics.balance >= 0, negative: statistics.balance < 0 }">
            ¥{{ Math.abs(statistics.balance || 0).toFixed(2) }}
          </text>
          <text class="overview-label">{{ statistics.balance >= 0 ? '账户结余' : '账户负债' }}</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <!-- 数据管理 -->
      <view class="menu-group">
        <view class="group-title">数据管理</view>
        <view class="menu-list">
          <view class="menu-item" @click="exportData">
            <view class="menu-left">
              <text class="menu-icon">📤</text>
              <text class="menu-text">导出数据</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="backupData">
            <view class="menu-left">
              <text class="menu-icon">💾</text>
              <text class="menu-text">数据备份</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="clearData">
            <view class="menu-left">
              <text class="menu-icon">🗑️</text>
              <text class="menu-text">清空数据</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
        </view>
      </view>

      <!-- 账户设置 -->
      <view class="menu-group">
        <view class="group-title">账户设置</view>
        <view class="menu-list">
          <view class="menu-item" @click="changePassword">
            <view class="menu-left">
              <text class="menu-icon">🔒</text>
              <text class="menu-text">修改密码</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="manageCategories">
            <view class="menu-left">
              <text class="menu-icon">📂</text>
              <text class="menu-text">分类管理</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="setBudget">
            <view class="menu-left">
              <text class="menu-icon">💰</text>
              <text class="menu-text">预算设置</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
        </view>
      </view>

      <!-- 应用设置 -->
      <view class="menu-group">
        <view class="group-title">应用设置</view>
        <view class="menu-list">
          <view class="menu-item" @click="notificationSettings">
            <view class="menu-left">
              <text class="menu-icon">🔔</text>
              <text class="menu-text">消息通知</text>
            </view>
            <view class="menu-right">
              <switch :checked="settings.notifications" @change="toggleNotifications" />
            </view>
          </view>
          <view class="menu-item" @click="privacySettings">
            <view class="menu-left">
              <text class="menu-icon">🛡️</text>
              <text class="menu-text">隐私设置</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="aboutApp">
            <view class="menu-left">
              <text class="menu-icon">ℹ️</text>
              <text class="menu-text">关于我们</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
        </view>
      </view>

      <!-- 帮助与反馈 -->
      <view class="menu-group">
        <view class="group-title">帮助与反馈</view>
        <view class="menu-list">
          <view class="menu-item" @click="userFeedback">
            <view class="menu-left">
              <text class="menu-icon">💬</text>
              <text class="menu-text">意见反馈</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="contactUs">
            <view class="menu-left">
              <text class="menu-icon">📞</text>
              <text class="menu-text">联系我们</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
          <view class="menu-item" @click="checkUpdate">
            <view class="menu-left">
              <text class="menu-icon">🔄</text>
              <text class="menu-text">检查更新</text>
              <text v-if="hasUpdate" class="update-badge">新版本</text>
            </view>
            <text class="menu-arrow">›</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 退出登录 -->
    <view class="logout-section">
      <button class="logout-btn" @click="logout">退出登录</button>
    </view>

    <!-- 修改密码弹窗 -->
    <uni-popup ref="passwordPopup" type="center" background-color="#fff">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">修改密码</text>
          <text class="popup-close" @click="closePasswordPopup">✕</text>
        </view>
        <view class="popup-body">
          <view class="input-group">
            <input
              v-model="passwordForm.oldPassword"
              class="input-field"
              :type="showOldPassword ? 'text' : 'password'"
              placeholder="请输入原密码"
            />
            <text class="password-toggle" @click="showOldPassword = !showOldPassword">
              {{ showOldPassword ? '隐藏' : '显示' }}
            </text>
          </view>
          <view class="input-group">
            <input
              v-model="passwordForm.newPassword"
              class="input-field"
              :type="showNewPassword ? 'text' : 'password'"
              placeholder="请输入新密码"
            />
            <text class="password-toggle" @click="showNewPassword = !showNewPassword">
              {{ showNewPassword ? '隐藏' : '显示' }}
            </text>
          </view>
          <view class="input-group">
            <input
              v-model="passwordForm.confirmPassword"
              class="input-field"
              :type="showConfirmPassword ? 'text' : 'password'"
              placeholder="请确认新密码"
            />
            <text class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
              {{ showConfirmPassword ? '隐藏' : '显示' }}
            </text>
          </view>
          <view v-if="passwordError" class="error-text">
            <text>{{ passwordError }}</text>
          </view>
        </view>
        <view class="popup-footer">
          <button class="popup-cancel" @click="closePasswordPopup">取消</button>
          <button class="popup-confirm" :disabled="!canChangePassword" @click="confirmChangePassword">
            确认修改
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-overlay">
      <view class="loading-content">
        <text class="loading-spinner"></text>
        <text class="loading-text">加载中...</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  data() {
    return {
      loading: false,
      hasUpdate: false,
      showOldPassword: false,
      showNewPassword: false,
      showConfirmPassword: false,
      passwordError: '',
      defaultAvatar: '/static/images/avatar-default.png',
      statistics: {
        totalRecords: 0,
        incomeRecords: 0,
        expenseRecords: 0,
        balance: 0
      },
      settings: {
        notifications: true,
        privacy: true,
        autoBackup: false
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    };
  },

  computed: {
    ...mapGetters(['userInfo', 'isLoggedIn']),
    
    // 是否可以修改密码
    canChangePassword() {
      return this.passwordForm.oldPassword && 
             this.passwordForm.newPassword &&
             this.passwordForm.confirmPassword &&
             this.passwordForm.newPassword === this.passwordForm.confirmPassword &&
             this.passwordForm.newPassword.length >= 6;
    }
  },

  onLoad() {
    this.initPage();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadUserStatistics();
  },

  onPullDownRefresh() {
    this.loadUserStatistics().finally(() => {
      uni.stopPullDownRefresh();
    });
  },

  methods: {
    ...mapActions(['logout', 'loadRecords']),

    // 初始化页面
    async initPage() {
      this.loading = true;
      try {
        await this.loadUserStatistics();
        await this.loadUserSettings();
      } catch (error) {
        console.error('初始化页面失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 加载用户统计数据
    async loadUserStatistics() {
      try {
        // 加载记账记录
        await this.loadRecords();
        
        // 计算统计数据
        const records = this.$store.state.records;
        const totalRecords = records.length;
        const incomeRecords = records.filter(record => record.type === 1).length;
        const expenseRecords = records.filter(record => record.type === 0).length;
        
        const totalIncome = records
          .filter(record => record.type === 1)
          .reduce((sum, record) => sum + parseFloat(record.amount), 0);
          
        const totalExpense = records
          .filter(record => record.type === 0)
          .reduce((sum, record) => sum + parseFloat(record.amount), 0);
        
        this.statistics = {
          totalRecords,
          incomeRecords,
          expenseRecords,
          balance: totalIncome - totalExpense
        };
        
      } catch (error) {
        console.error('加载用户统计失败:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    },

    // 加载用户设置
    async loadUserSettings() {
      try {
        // 从本地存储加载设置
        const settings = uni.getStorageSync('userSettings') || this.settings;
        this.settings = { ...this.settings, ...settings };
      } catch (error) {
        console.error('加载用户设置失败:', error);
      }
    },

    // 保存用户设置
    saveUserSettings() {
      try {
        uni.setStorageSync('userSettings', this.settings);
      } catch (error) {
        console.error('保存用户设置失败:', error);
      }
    },

    // 编辑个人资料
    editProfile() {
      uni.navigateTo({
        url: '/pages/edit-profile/edit-profile'
      });
    },

    // 更换头像
    changeAvatar() {
      uni.showActionSheet({
        itemList: ['拍照', '从相册选择'],
        success: (res) => {
          const tapIndex = res.tapIndex;
          if (tapIndex === 0) {
            this.chooseImage('camera');
          } else if (tapIndex === 1) {
            this.chooseImage('album');
          }
        }
      });
    },

    // 选择图片
    chooseImage(sourceType) {
      uni.chooseImage({
        count: 1,
        sourceType: [sourceType],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadAvatar(tempFilePath);
        }
      });
    },

    // 上传头像
    uploadAvatar(filePath) {
      uni.showLoading({
        title: '上传中...'
      });

      // 模拟上传过程
      setTimeout(() => {
        uni.hideLoading();
        
        // 在实际项目中，这里应该调用上传接口
        // 现在只是模拟上传成功
        const newAvatar = filePath;
        
        // 更新用户头像（模拟）
        const updatedUserInfo = {
          ...this.userInfo,
          avatar: newAvatar
        };
        
        this.$store.commit('SET_USER_INFO', updatedUserInfo);
        
        uni.showToast({
          title: '头像更新成功',
          icon: 'success'
        });
      }, 2000);
    },

    // 查看记录
    viewRecords(type) {
      if (type === 1) {
        // 查看收入记录
        uni.navigateTo({
          url: '/pages/record-list/record-list?type=1'
        });
      } else {
        // 查看支出记录
        uni.navigateTo({
          url: '/pages/record-list/record-list?type=0'
        });
      }
    },

    // 跳转到统计页面
    navigateToStatistics() {
      uni.switchTab({
        url: '/pages/statistics/statistics'
      });
    },

    // 导出数据
    exportData() {
      uni.showActionSheet({
        itemList: ['导出为Excel', '导出为CSV', '导出为PDF'],
        success: (res) => {
          const formats = ['Excel', 'CSV', 'PDF'];
          uni.showLoading({
            title: `正在导出${formats[res.tapIndex]}...`
          });
          
          // 模拟导出过程
          setTimeout(() => {
            uni.hideLoading();
            uni.showToast({
              title: `${formats[res.tapIndex]}导出成功`,
              icon: 'success'
            });
          }, 2000);
        }
      });
    },

    // 数据备份
    backupData() {
      uni.showModal({
        title: '数据备份',
        content: '是否将数据备份到云端？',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '备份中...'
            });
            
            // 模拟备份过程
            setTimeout(() => {
              uni.hideLoading();
              uni.showToast({
                title: '数据备份成功',
                icon: 'success'
              });
            }, 1500);
          }
        }
      });
    },

    // 清空数据
    clearData() {
      uni.showModal({
        title: '清空数据',
        content: '此操作将删除所有记账记录，且不可恢复。确定要清空吗？',
        confirmColor: '#FF3B30',
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({
              title: '清空中...'
            });
            
            // 模拟清空过程
            setTimeout(() => {
              uni.hideLoading();
              
              // 在实际项目中，这里应该调用清空数据的API
              this.$store.commit('SET_RECORDS', []);
              this.loadUserStatistics();
              
              uni.showToast({
                title: '数据清空成功',
                icon: 'success'
              });
            }, 1000);
          }
        }
      });
    },

    // 修改密码
    changePassword() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      this.passwordError = '';
      this.$refs.passwordPopup.open();
    },

    // 关闭修改密码弹窗
    closePasswordPopup() {
      this.$refs.passwordPopup.close();
    },

    // 确认修改密码
    async confirmChangePassword() {
      if (!this.canChangePassword) {
        return;
      }

      this.loading = true;

      try {
        // 模拟修改密码API调用
        // 在实际项目中，这里应该调用修改密码的接口
        await new Promise((resolve) => {
          setTimeout(resolve, 1500);
        });

        this.closePasswordPopup();
        uni.showToast({
          title: '密码修改成功',
          icon: 'success'
        });

      } catch (error) {
        console.error('修改密码失败:', error);
        this.passwordError = error.message || '修改密码失败';
      } finally {
        this.loading = false;
      }
    },

    // 分类管理
    manageCategories() {
      uni.navigateTo({
        url: '/pages/category-manage/category-manage'
      });
    },

    // 预算设置
    setBudget() {
      uni.navigateTo({
        url: '/pages/budget-set/budget-set'
      });
    },

    // 切换通知设置
    toggleNotifications(e) {
      this.settings.notifications = e.detail.value;
      this.saveUserSettings();
    },

    // 通知设置
    notificationSettings() {
      uni.navigateTo({
        url: '/pages/notification-settings/notification-settings'
      });
    },

    // 隐私设置
    privacySettings() {
      uni.navigateTo({
        url: '/pages/privacy-settings/privacy-settings'
      });
    },

    // 关于应用
    aboutApp() {
      uni.navigateTo({
        url: '/pages/about-app/about-app'
      });
    },

    // 用户反馈
    userFeedback() {
      uni.navigateTo({
        url: '/pages/feedback/feedback'
      });
    },

    // 联系我们
    contactUs() {
      uni.makePhoneCall({
        phoneNumber: '400-123-4567'
      });
    },

    // 检查更新
    checkUpdate() {
      uni.showLoading({
        title: '检查中...'
      });

      // 模拟检查更新
      setTimeout(() => {
        uni.hideLoading();
        
        if (this.hasUpdate) {
          uni.showModal({
            title: '发现新版本',
            content: '发现新版本 v2.0.0，是否立即更新？',
            success: (res) => {
              if (res.confirm) {
                uni.showLoading({
                  title: '下载中...'
                });
                
                setTimeout(() => {
                  uni.hideLoading();
                  uni.showToast({
                    title: '更新成功',
                    icon: 'success'
                  });
                  this.hasUpdate = false;
                }, 2000);
              }
            }
          });
        } else {
          uni.showToast({
            title: '已是最新版本',
            icon: 'none'
          });
        }
      }, 1000);
    },

    // 退出登录
    logout() {
      uni.showModal({
        title: '退出登录',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            this.$store.dispatch('logout');
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 100rpx;
}

/* 用户信息头部 */
.user-header {
  position: relative;
  margin-bottom: 30rpx;
}

.user-bg {
  height: 300rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-info {
  position: absolute;
  top: 100rpx;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 0 40rpx;
}

.avatar-section {
  position: relative;
  margin-right: 30rpx;
}

.user-avatar {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  border: 4rpx solid white;
  background-color: #f0f0f0;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 44rpx;
  height: 44rpx;
  background: #007AFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid white;
}

.edit-icon {
  color: white;
  font-size: 20rpx;
  font-weight: bold;
}

.user-details {
  flex: 1;
}

.user-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 10rpx;
}

.user-email,
.user-phone {
  display: block;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 5rpx;
}

.edit-profile {
  padding: 16rpx 24rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  backdrop-filter: blur(10px);
}

.edit-text {
  font-size: 24rpx;
  color: white;
}

/* 账户概览 */
.account-overview {
  background: white;
  margin: 0 30rpx 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.overview-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.overview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 30rpx;
}

.overview-item {
  text-align: center;
  padding: 30rpx 20rpx;
  background: #f8f9fa;
  border-radius: 16rpx;
  transition: all 0.3s;
}

.overview-item:active {
  background: #e9ecef;
  transform: scale(0.98);
}

.overview-number {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #007AFF;
  margin-bottom: 15rpx;
}

.overview-number.positive {
  color: #34C759;
}

.overview-number.negative {
  color: #FF3B30;
}

.overview-label {
  font-size: 24rpx;
  color: #666;
}

/* 菜单区域 */
.menu-section {
  margin: 0 30rpx;
}

.menu-group {
  background: white;
  border-radius: 20rpx;
  margin-bottom: 30rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.group-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-list {
  padding: 0;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s;
}

.menu-item:active {
  background-color: #f8f9fa;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.menu-icon {
  font-size: 36rpx;
  margin-right: 20rpx;
  width: 40rpx;
  text-align: center;
}

.menu-text {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.update-badge {
  background: #FF3B30;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  margin-left: 15rpx;
}

.menu-arrow {
  font-size: 36rpx;
  color: #999;
  margin-left: 20rpx;
}

.menu-right {
  display: flex;
  align-items: center;
}

/* 退出登录 */
.logout-section {
  margin: 50rpx 30rpx 0;
}

.logout-btn {
  width: 100%;
  height: 100rpx;
  background: #FF3B30;
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.logout-btn:active {
  background: #D70015;
}

/* 弹窗样式 */
.popup-content {
  width: 600rpx;
  background: white;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 32rpx;
  color: #999;
  padding: 10rpx;
}

.popup-body {
  padding: 40rpx 30rpx;
}

.input-group {
  position: relative;
  margin-bottom: 30rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
}

.input-field {
  flex: 1;
  height: 100rpx;
  font-size: 32rpx;
  color: #333;
  background: transparent;
}

.password-toggle {
  padding: 10rpx 20rpx;
  background: rgba(0, 122, 255, 0.1);
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #007AFF;
}

.error-text {
  margin-top: 20rpx;
  text-align: center;
}

.error-text text {
  font-size: 24rpx;
  color: #FF3B30;
}

.popup-footer {
  display: flex;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;
  gap: 20rpx;
}

.popup-cancel,
.popup-confirm {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 32rpx;
}

.popup-cancel {
  background: #f8f9fa;
  color: #666;
}

.popup-confirm {
  background: #007AFF;
  color: white;
}

.popup-confirm:disabled {
  background: #CCCCCC;
  color: #999;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.loading-content {
  background: white;
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f0f0f0;
  border-top: 6rpx solid #007AFF;
  border-radius: 50%;
  margin-bottom: 30rpx;
  animation: spin 1s linear infinite;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>